package com.ocean.tree;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Stack;

/**
 * https://leetcode.cn/problems/binary-tree-inorder-traversal/
 * 中序遍历
 */
public class BinaryTreeInorderTraversal {


    public static void main(String[] args) {
        TreeNode root = TreeNode.getRoot();
        BinaryTreeInorderTraversal traversal = new BinaryTreeInorderTraversal();
        List<Integer> res = traversal.inorderTraversal2(root);
        System.out.println(res);
    }

    /**
     * 中序遍历：左->根->右
     * 前序遍历：根->左->右
     * 后序变量：左->右->根
     *
     * @param root
     * @return
     */
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        traversal(root, result);
        return result;
    }


    private void traversal(TreeNode root, List<Integer> all) {
        if (root == null) {
            return;
        }
        traversal(root.getLeft(), all);
        all.add(root.getValue());
        traversal(root.getRight(), all);
    }


    private List<Integer> inorderTraversal2(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        while (root != null || !stack.isEmpty()) {
            while (root != null) {
                stack.push(root);
                root = root.getLeft();
            }
            root = stack.pop();
            result.add(root.getValue());
            root = root.getRight();
        }
        return result;
    }

}
